import * as path from "path";
import * as chokidar from "chokidar";
import { execSync } from "child_process";

const JSON_FILE_PATH = "./api.json";
const MODULE_DECL_PATH = "./module_declarations.toml";
const API_FILE_PATH = "./src/api.ts";
const GEN_API_CMD = `gen_api -i ${JSON_FILE_PATH} -m ${MODULE_DECL_PATH} -n ${API_FILE_PATH}`;

export function ApiJsonWatcherPlugin() {
  return {
    name: "api-json-watcher",
    handleHotUpdate({ file }: { file: string }) {
      const apiJsonPath = path.resolve(__dirname, JSON_FILE_PATH);
      console.log("api-json-watcher found update", file);

      if (file === apiJsonPath) {
        try {
          // 执行 gen_api 命令，生成 api.ts 文件
          execSync(GEN_API_CMD, {
            stdio: "inherit",
            env: process.env,
          });
          console.log("api.json has been changed, api.ts has been generated.");
        } catch (error) {
          console.error("Error executing gen_api command:", error);
        }
      }
    },
    setup() {
      console.log("watcher-setup");
      const watcher = chokidar.watch(path.resolve(__dirname, JSON_FILE_PATH));

      watcher.on("change", (filePath) => {
        this.handleHotUpdate({ file: filePath });
      });

      return () => {
        watcher.close();
      };
    },
  };
}
